// import axios, {
//   InternalAxiosRequestConfig,
//   AxiosResponse,
//   AxiosPromise,
// } from "axios";
// import { useUserStore } from "@/store/modules/user";

// // 引入qs模块，对数据进行序列化
// // import QS from "qs";
// import nProgress from "nprogress";
// import "nprogress/nprogress.css";

import axios, { InternalAxiosRequestConfig, AxiosResponse } from "axios";
import { useUserStore } from "@/store";
import { useRouter } from 'vue-router'
import { ResultEnum } from "@/enums/ResultEnum";
import { TOKEN_KEY } from "@/enums/CacheEnum";
import qs from "qs";
import { createMessage } from "@/Public-UIlibrary/pb-message/method";

const router = useRouter()
// 创建 axios 实例
const service = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: 50000,
  headers: { "Content-Type": "application/json;charset=utf-8", "x-application": import.meta.env.VITE_APP_Application },
  paramsSerializer: (params) => {
    return qs.stringify(params);
  },
});

// 请求拦截器
service.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    const accessToken = localStorage.getItem("pinia_token");
    if (accessToken) {
      config.headers['x-token'] = accessToken;
    }
    if (config.method?.toUpperCase() === "GET") {
      config.data = true; //设置data使get方法设置请求头生效
    }
    // config.headers["Token"] =
    //   userStore.pinia_token || localStorage.getItem("pinia_token");
    return config;
  },
  (error: any) => {
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response: AxiosResponse) => {
    const userStore = useUserStore();
    // console.log(response,'response',ResultEnum.SUCCESS)
    const { code, msg, data } = response.data;
    if (response.config.responseType == 'blob' && response.status === 200) {
      if (!response.headers['content-disposition']) {
        const fileReader: any = new FileReader()
        fileReader.readAsText(new Blob([response.data], { type: 'application/json' }), 'utf-8')
        fileReader.onload = () => {
          const datamsg = JSON.parse(fileReader.result)
          createMessage({
            message: datamsg ? datamsg.msg : '导出失败',
            type: 'error'
          })
        }
      } else {
        createMessage({
          message: '导出中...'
        })
      }

      return response
    }
    if (response.status === 200) {
      if (code == 4010) {
        userStore.logout();
      } else if (code == 2000 || code == 5002) {
        return response.data;
      } else {
        createMessage({
          message: msg || "系统出错",
          type: 'error'
        })
        return response.data
      }
    } else {
      createMessage({
        message: msg || "系统出错",
        type: 'error'
      })
      return Promise.reject(new Error(msg || "Error"));
    }
    // 检查配置的响应类型是否为二进制类型（'blob' 或 'arraybuffer'）, 如果是，直接返回响应对象
    // if (
    //   response.config.responseType === "blob" ||
    //   response.config.responseType === "arraybuffer"
    // ) {
    //   return response;
    // }

    // const { code, data, msg } = response.data;
    // if (code === ResultEnum.SUCCESS) {
    //   return data;
    // }

    // ElMessage.error(msg || "系统出错");
    // return Promise.reject(new Error(msg || "Error"));
  },
  (error: any) => {
    // console.log(error,'error')
    // 异常处理
    if (error.response) {
      const userStore = useUserStore();
      const { status } = error.response;
      // token 过期,重新登录
      switch (status) {
        case 400:
          ElMessage.error("错误请求(400)");
          break;
        case 401:
          ElMessage.error("未授权,请重新登录(401)");
          userStore.logout();
          break;
        case 403:
          ElMessage.error("拒绝访问(403)");
          console.log(status, "dkjfdjkfj");
          userStore.logout();
          break;
        case 404:
          ElMessage.error("请求错误,未找到该资源(404)");
          break;
        case 405:
          ElMessage.error("错误请求(405)");
          break;
        case 408:
          ElMessage.error("请求超时(408)");
          break;
        case 500:
          ElMessage.error("服务器错误(500)");
          break;
        case 501:
          ElMessage.error("服务未实现(501)");
          break;
        case 502:
          ElMessage.error("网络错误(502)");
          break;
        case 503:
          ElMessage.error("服务不可用(503)");
          break;
        case 504:
          ElMessage.error("网络超时(504)");
          break;
        case 505:
          ElMessage.error("HTTP版本不受支持(505)");
          break;
        default:
          ElMessage.error("网络出现问题,请稍后再试");
          break;
      }
    }
    return Promise.reject(error.message);
  }
);

// 导出 axios 实例
export default service;
